package org.chpro.jdbc;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

/**
 * dbutils 的模版类
 * @author Administrator
 *
 */
public class DbUtilTemplate {
	private DataSource dataSource;
	
	private QueryRunner queryRunner;
	
	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	public QueryRunner getQueryRunner(){
		if(queryRunner==null){
			queryRunner = new QueryRunner(dataSource);
		}
		return queryRunner;
	}
	
	/**
	 * 将查询结果转换成List<Map<String,Object>>
	 * @param sql
	 * @return
	 */
	public List<Map<String,Object>> queryForList(String sql){
		try {
			return getQueryRunner().query(sql,new MapListHandler());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 将查询结果转换成List<Map<String,Object>> 可以传参数的重载方法
	 * @param sql
	 * @return
	 */
	public List<Map<String,Object>> queryForList(String sql,Object... args){
		try {
			return getQueryRunner().query(sql,new MapListHandler(),args);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
		
		}
		return null;
	}
	
	
	/**
	 * 返回类实体集合
	 * @param sql
	 * @param cls
	 * @return
	 */
	public <T> T queryForList(String sql,Class cls){
		try {
			return (T) getQueryRunner().query(sql, new BeanListHandler(cls));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
		}
		return null;
		
	}
	
	/**
	 * 返回类实体集合 可以传参数
	 * @param sql
	 * @param cls
	 * @return
	 */
	public <T> T queryForList(String sql,Class cls,Object... args){
		try {
			return (T) getQueryRunner().query(sql, new BeanListHandler(cls),args);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			
		}
		return null;
		
	}
	
	/**
	 * 修改 删除 添加 操作
	 * @param sql
	 * @param args  
	 * @return
	 */
	public Integer update(String sql,Object... args){
		try {
			return getQueryRunner().update(sql,args);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			
		}
		return null;
	}
	
	/**
	 * 批量 添加 修改 删除
	 * @param sql
	 * @param params
	 * @return
	 */
	public int[] batch(String sql,Object[][] params){
		try {
			return getQueryRunner().batch(sql, params);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			
		}
		return null;
	}
}
